#!/bin/bash

#BY MBY

num=0    #num of homeworks
file_dir=/home/homework 
num1=0   #flag of answer
score=0
name=" "
id=" "

#clear the content of status and grade
> $file_dir/grades/status.txt
> $file_dir/grades/grade.txt

#header of grade.txt
echo "  student              score" >> /home/homework/grades/grade.txt 

#read answer.txt
c=0
for line in `cat /home/homework/grades/answer.txt`
do
	answer=$line
	answers[$c]=$answer
	((c++))
done




traverse_dir()
{

	filepath=$1
	cd $filepath
    	for file in `ls -ltr *.txt`
	do
		if [ -d ${filepath}/$file ]
		then
			if [[ $file != '.' && $file != '..' ]]
			then
				traverse_dir ${filepath}/$file
			fi
		else
			check_suffix ${filepath}/$file
		fi
	done
	echo "  " >> /home/homework/grades/status.txt
	echo "  total number of assignments handed in: $num" >> /home/homework/grades/status.txt
}


check_suffix()
{
	file=$1
	if [ "${file##*.}"x = "txt"x ] || [ "${file##*.}"x = "ini"x ];then
	let num=num+1
	echo "number of homeworks":$num
	echo $file
	#cat $file | while read line

	for line in `cat $file`
	do
	  echo $line
	  echo answer:${answers[$num2]}
	    if test "$line" == "${answers[$num2]}"
		then 
		let score=score+1
	    fi
	  let num2=num2+1
	done
	echo $score fen
	echo "  ${file:0-18:14}" >> /home/homework/grades/status.txt
	echo "  ${file:0-18:14}         $score" >> /home/homework/grades/grade.txt
	fi   
	
	let num2=0
	let score=0
}

chmod ug+w o-w $file_dir/grades/grade.txt
chmod ug+w o-w $file_dir/grades/status.txt

traverse_dir $file_dir


